﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using ComClassLibrary;
using KeyboardArg;
using System.Diagnostics;


namespace InputTool
{
    static class Program
    {
        public static bool IsSimulation = false; //模拟环境

        private static string ToolName = "InputTool_Program";

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            XDLog.WriteLog(ToolName, strClass, "in");
            KillExistProgress();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);           
            string jsonString = "";
            if (args.Length <= 0)
            {
                jsonString = "{\"Content\":\"张山\",\"Key\":null,\"Lang\":null,\"MaxLength\":5,\"Title\":\"请输入你的测试姓名\",\"VoiceFileName\":null,\"Wnd\":{\"value\":5903714}}";
            }
            else
            {
                jsonString = args[0].Replace('@', '"'); ;
            }
            KeyBoardArgs keyboardArg = null;
            try
            {
                XDLog.WriteLog(ToolName, strClass, jsonString);
                keyboardArg = JsonHandler.ConvertToJsonObject<KeyBoardArgs>(jsonString);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                XDLog.WriteLog(ToolName, strClass, e.ToString());
                MessageBox.Show(e.ToString(), "参数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (null == keyboardArg)
            {
                XDLog.WriteLog(ToolName, strClass, "参数错误, 启动失败.");
                MessageBox.Show(jsonString, "参数错误", MessageBoxButtons.OK, MessageBoxIcon.Error); //20170412 取消提示
                return;
            }
            Application.Run(new FormInputTool(keyboardArg)); 
        }

        private static void KillExistProgress()
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Process p = Process.GetCurrentProcess();        
            Process[] processes = Process.GetProcesses();
            foreach (System.Diagnostics.Process process in processes)
            {
                if (process.ProcessName.Contains("InputTool") && p.Id != process.Id)
                {
                    XDLog.WriteLog(ToolName, strClass, "发现已存在进程，开始等待进程退出.");
                    process.WaitForExit(2000);
                    if (!process.HasExited)
                    {
                        process.Kill();
                        XDLog.WriteLog(ToolName, strClass, "强制退出老进程");
                    }
                    XDLog.WriteLog(ToolName, strClass, "老进程已经退出.");
                }
            }        
        }
    }
}